import datetime
import hashlib
import os
import random
import time
from urllib.parse import parse_qs
from app.alipay import alipay
from django.core.cache import cache
from django.http import JsonResponse, HttpResponse, StreamingHttpResponse
from django.shortcuts import render, redirect
from django.views.decorators.csrf import csrf_exempt

from app.models import User, Cart, Indexbanersll, Indexdrb, Indexlouti, \
    Goods5, Indexmrb, AppOrdergoods, AppOrder, CaoYaoKind, CaoYao, Pinglun, Yijian, Shoucang, History


def base(request):
    token = request.session.get('token')
    userid = cache.get(token)
    response_data = {
        'user': None
    }

    if userid:
        user = User.objects.get(pk=userid)
        response_data['user'] = user

    return render(request, 'base/base.html', context=response_data)


def admin(request):
    caoyao = CaoYao.objects.all()
    caoyaokind = CaoYaoKind.objects.all()
    pinglun = Pinglun.objects.all()
    user = User.objects.all()
    data = {
        'caoyaonum': len(caoyao),
        'caoyaokindnum': len(caoyaokind),
        'pinglunnum': len(pinglun),
        'usernum': len(user)
    }
    token = request.session.get('token')
    userid = cache.get(token)
    if userid:
        user = User.objects.get(pk=userid)
        data['user'] = user
    return render(request, 'admin/index.html', context=data)


def creatCaoyao(request):
    return render(request, 'admin/creatCaoyao.html')


def creatCaoyaokind(request):
    return render(request, 'admin/creatCaoyaoKind.html')


def submitCaoyao(request):
    yao = CaoYao()
    yao.name = request.POST['name']
    yao.kind = request.POST['kind']
    yao.jianjie = request.POST['jianjie']
    yao.gongxiao = request.POST['gongxiao']
    yao.images = request.POST['images']
    yao.save()
    return render(request, 'admin/success.html', context={'what': "新建草药"})


def submitCaoyaoKind(request):
    kind = CaoYaoKind()
    kind.kind_name = request.POST['name']
    kind.kind_tuijian = request.POST['tuijian']
    kind.save()
    return render(request, 'admin/success.html', context={'what': "新建草药种类"})


def modifyUser(request):
    Color = ["primary", "success", "info", "warning", "danger", "success"]
    user = User.objects.filter(type=0)
    data = []
    for i in range(0, len(user)):
        onedata = {'user': user[i], 'color': Color[i % 4]}
        data.append(onedata)

    info = {
        'zus': data
    }
    return render(request, 'admin/modifyUser.html', context=info)


def modifyMe(request):
    token = request.session.get('token')
    userid = cache.get(token)
    Color = ["primary", "success", "info", "warning", "danger", "success"]
    user = User.objects.filter(id=userid)
    data = []
    for i in range(0, len(user)):
        onedata = {'user': user[i], 'color': Color[i % 4]}
        data.append(onedata)

    info = {
        'zus': data
    }
    return render(request, 'index/modifyMe.html', context=info)

def MyShouCang(request):
    token = request.session.get('token')
    userid = cache.get(token)
    Color = ["primary", "success", "info", "warning", "danger", "success"]
    shoucang = Shoucang.objects.filter(ren=userid)
    data = []
    for i in range(0, len(shoucang)):
        get = CaoYao.objects.get(pk=shoucang[i].caoyao)
        onedata = {'shoucang': get, 'color': Color[i % 4]}
        data.append(onedata)

    info = {
        'zus': data
    }
    return render(request, 'index/MyShouCang.html', context=info)

def history(request):
    token = request.session.get('token')
    userid = cache.get(token)
    Color = ["primary", "success", "info", "warning", "danger", "success"]
    shoucang = History.objects.filter(ren=userid)
    data = []
    for i in range(0, len(shoucang)):
        get = CaoYao.objects.get(pk=shoucang[i].caoyao)
        onedata = {'shoucang': get, 'color': Color[i % 4],'shijian':shoucang[i].shijian}
        data.append(onedata)

    info = {
        'zus': data
    }
    return render(request, 'index/history.html', context=info)


def submitModifyUser(request):
    yao = User.objects.get(id=request.POST['id'])
    yao.mobile = request.POST['mobile']
    yao.pwd = request.POST['pwd']
    yao.nianji = request.POST['nianji']
    yao.xingbie = request.POST['xingbie']
    yao.save()
    return render(request, 'admin/success.html', context={'what': "修改学生信息"})

def submitModifyMe(request):
    yao = User.objects.get(id=request.POST['id'])
    yao.mobile = request.POST['mobile']
    yao.pwd = request.POST['pwd']
    yao.nianji = request.POST['nianji']
    yao.xingbie = request.POST['xingbie']
    yao.save()
    return render(request, 'index/success.html', context={'what': "修改个人信息"})


def deleteUser(request):
    Color = ["primary", "success", "info", "warning", "danger", "success"]
    user = User.objects.filter(type=0)
    data = []
    for i in range(0, len(user)):
        onedata = {'user': user[i], 'color': Color[i % 4]}
        data.append(onedata)

    info = {
        'zus': data
    }
    return render(request, 'admin/deleteUser.html', context=info)


def submitDeleteUser(request):
    yao = User.objects.get(id=request.POST['id'])
    yao.delete()
    return render(request, 'admin/success.html', context={'what': "删除学生信息"})


def deletePinglun(request):
    Color = ["primary", "success", "info", "warning", "danger", "success"]
    pinglun = Pinglun.objects.all()
    data = []
    for i in range(0, len(pinglun)):
        onedata = {'pinglun': pinglun[i], 'color': Color[i % 4]}
        data.append(onedata)

    info = {
        'zus': data
    }
    return render(request, 'admin/deletePinglun.html', context=info)


def submitDeletePinglun(request):
    yao = Pinglun.objects.get(pl_id=request.POST['id'])
    yao.delete()
    return render(request, 'admin/success.html', context={'what': "删除评论信息"})


def modifyCaoyao(request):
    Color = ["primary", "success", "info", "warning", "danger", "success"]
    yao = CaoYao.objects.all()
    data = []
    for i in range(0, len(yao)):
        onedata = {'caoyao': yao[i], 'color': Color[i % 4]}
        data.append(onedata)

    info = {
        'zus': data
    }
    return render(request, 'admin/modifyCaoYao.html', context=info)


def submitModifyCaoyao(request):
    yao = CaoYao.objects.get(id=request.POST['id'])
    yao.name = request.POST['name']
    yao.kind = request.POST['kind']
    yao.jianjie = request.POST['jianjie']
    yao.gongxiao = request.POST['gongxiao']
    yao.images = request.POST['images']
    yao.xiaoneizhongzhidizhi = request.POST['xiaoneizhongzhidizhi']
    yao.save()
    return render(request, 'admin/success.html', context={'what': "修改草药"})


def modifyCaoyaoKind(request):
    Color = ["primary", "success", "info", "warning", "danger", "success"]
    yao = CaoYaoKind.objects.all()
    data = []
    for i in range(0, len(yao)):
        onedata = {'caoyao': yao[i], 'color': Color[i % 4]}
        data.append(onedata)

    info = {
        'zus': data
    }
    return render(request, 'admin/modifyCaoYaoKind.html', context=info)


def submitModifyCaoyaoKind(request):
    yao = CaoYaoKind.objects.get(id=request.POST['id'])
    yao.kind_name = request.POST['name']
    yao.kind_tuijian = request.POST['kind']
    yao.save()
    return render(request, 'admin/success.html', context={'what': "修改草药种类"})


def deleteCaoyao(request):
    Color = ["primary", "success", "info", "warning", "danger", "success"]
    yao = CaoYao.objects.all()
    data = []
    for i in range(0, len(yao)):
        onedata = {'caoyao': yao[i], 'color': Color[i % 4]}
        data.append(onedata)

    info = {
        'zus': data
    }
    return render(request, 'admin/deleteCaoYao.html', context=info)


def submitDeleteCaoyao(request):
    yao = CaoYao.objects.get(id=request.POST['id'])
    yao.delete()
    return render(request, 'admin/success.html', context={'what': "删除草药"})


def deleteCaoyaoKind(request):
    Color = ["primary", "success", "info", "warning", "danger", "success"]
    yao = CaoYaoKind.objects.all()
    data = []
    for i in range(0, len(yao)):
        onedata = {'caoyao': yao[i], 'color': Color[i % 4]}
        data.append(onedata)

    info = {
        'zus': data
    }
    return render(request, 'admin/deleteCaoYaoKind.html', context=info)


def submitDeleteCaoyaoKind(request):
    yao = CaoYaoKind.objects.get(id=request.POST['id'])
    yao.delete()
    return render(request, 'admin/success.html', context={'what': "删除草药种类"})


def index(request):
    # 轮播图数据
    baners = Indexbanersll.objects.all()
    allCaoYao = CaoYao.objects.all()

    # 草药种类
    caoyaokinds = CaoYaoKind.objects.all()
    caoyaoinfo = []
    for i in caoyaokinds:
        query_set = CaoYao.objects.filter(kind=i.pk)
        oneinfo = {'kind': i.kind_name, 'caoyao': query_set}
        caoyaoinfo.append(oneinfo)

    data = {
        'title': '首页',
        'baners': baners,
        'user': None,
        'caoyaoinfo': caoyaoinfo,
        'bottom': allCaoYao[0:5]
    }

    token = request.session.get('token')
    userid = cache.get(token)
    if userid:
        user = User.objects.get(pk=userid)
        data['user'] = user

    return render(request, 'index/index.html', context=data)


def generate_password(param):
    md5 = hashlib.md5()
    md5.update(param.encode('utf-8'))
    md5.hexdigest
    return md5.hexdigest()


def generate_token():
    token = str(time.time()) + str(random.random())
    md5 = hashlib.md5()
    md5.update(token.encode('utf-8'))
    return md5.hexdigest()


def register(request):
    if request.method == 'GET':
        return render(request, 'register/register.html')
    elif request.method == 'POST':
        user = User()
        user.mobile = request.POST.get('mobile')
        user.xingbie = request.POST.get('xingbie')
        user.nianji = request.POST.get('nianji')
        user.type = 0
        user.pwd = generate_password(request.POST.get('pwd'))
        user.save()
        # 状态保持
        token = generate_token()
        cache.set(token, user.id, 60 * 60 * 24 * 3)
        request.session['token'] = token
        return redirect('bbf:index')
    return render(request, 'register/register.html')


def checkmobile(request):
    mobile = request.GET.get('mobile')
    users = User.objects.filter(mobile=mobile)
    if users.exists():
        response_data = {
            'status': 0,
            'msg': '帐号被占用'
        }
    else:
        response_data = {
            'status': 1,
            'msg': '帐号可用'
        }

    return JsonResponse(response_data)


def login(request):
    if request.method == 'GET':
        return render(request, 'login/login.html')
    elif request.method == 'POST':
        account = request.POST.get('account')
        pwd = request.POST.get('pwd')
        # 重定向
        back = request.COOKIES.get('back')

        users = User.objects.filter(mobile=account)

        if users.exists():
            user = users.first()
            if user.pwd == generate_password(pwd):
                token = generate_token()
                cache.set(token, user.id, 60 * 60 * 24 * 3)
                # 传递给客户端
                request.session['token'] = token
                if user.type == 1:
                    return redirect('bbf:admin')
                elif back == 'product_details':
                    return redirect('bbf:product_detailsbase')
                elif back == 'cart':
                    return redirect('bbf:cart')
                else:
                    return redirect('bbf:index')

            else:
                return render(request, 'login/login.html', context={'ps_err': '密码错误'})

        else:
            return render(request, 'login/login.html', context={'user_err': '用户名不存在'})
    return render(request, 'login/login.html')


def logout(request):
    request.session.flush()
    return redirect('bbf:login')

def shoucang(request):
    ren = request.GET.get('ren')
    caoyao = request.GET.get('caoyao')
    shoucang = Shoucang.objects.filter(ren=ren,caoyao=caoyao)
    if shoucang.exists():
        shoucang.delete()
    else:
        new = Shoucang()
        new.ren = ren
        new.caoyao = caoyao
        new.save()
    return redirect('/bbf/product_details?id='+caoyao)


def product_details(request):
    id = int(request.GET.get('id'))
    token = request.session.get('token')
    userid = cache.get(token)
    history = History()
    history.caoyao = id
    history.ren = userid
    history.shijian = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
    history.save()
    caoyaoDetail = CaoYao.objects.get(id=id)
    cao_yao_kind = CaoYaoKind.objects.get(id=caoyaoDetail.kind)
    pingluns = Pinglun.objects.filter(duixiang=id)
    pingluninfo = []
    tuijian = CaoYao.objects.get(pk=cao_yao_kind.kind_tuijian)
    shoucang = Shoucang.objects.filter(caoyao=id)
    if shoucang.exists():
        shoucangString = ""
    else:
        shoucangString = "-empty"

    for i in pingluns:
        oneInfo = {'pinglun': i, 'pinglunren': User.objects.get(id=i.pinglunren)}
        pingluninfo.append(oneInfo)
    data = {
        'caoyaoDetail': caoyaoDetail,
        'cao_yao_kind': cao_yao_kind,
        'pingluninfo': pingluninfo,
        'tuijian': tuijian,
        'shoucangString':shoucangString
    }

    if userid:
        user = User.objects.get(pk=userid)
        data['user'] = user

    return render(request, 'product_details/product_details.html', context=data)


def pinglun(request):
    token = request.session.get('token')
    userid = cache.get(token)
    pinglun = Pinglun()
    duixiang = request.POST.get("duixiang")
    pinglunneirong = request.POST.get("pinglunneirong")
    pinglun.duixiang = duixiang
    pinglun.pinglunren = userid
    pinglun.pinglunneirong = pinglunneirong
    pinglun.pinglunshijian = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
    pinglun.save()
    return render(request, 'product_details/success.html')


def cart(request):
    token = request.session.get('token')
    userid = cache.get(token)
    if userid:
        user = User.objects.get(pk=userid)
        carts = user.cart_set.filter(number__gt=0)

        isall = True
        for cart in carts:
            if not cart.isselect:
                isall = False

        data = {
            'carts': carts,
            'isall': isall,
            'user': user,
        }

        return render(request, 'cart/cart.html', context=data)
    else:
        return render(request, 'login/login.html')


def cart_count(request):
    token = request.session.get('token')
    userid = cache.get(token)

    numbers = 0  # 商品总件数
    if userid:
        user = User.objects.get(pk=userid)
        carts = user.cart_set.all()

        for cart in carts:
            numbers += cart.number
        response_data = {
            'status': 1,
            'numbers': numbers
        }
    else:
        response_data = {
            'status': -1,
            'numbers': 0
        }
    return JsonResponse(response_data)


def mine(request):
    token = request.session.get('token')
    userid = cache.get(token)
    response_data = {
        'user': None
    }

    if userid:
        user = User.objects.get(pk=userid)
        response_data['user'] = user
        orders = user.order_set.all()
        response_data['waitpay'] = orders.filter(status=0).count()  # 待支付订单数
        response_data['paydone'] = orders.filter(status=1).count()  # 已支付订单数
        response_data['receive'] = orders.filter(status=2).count()  # 已支付订单数

    return render(request, 'mine/mine.html', context=response_data)


def addgoods(request):
    token = request.session.get('token')
    response_data = {}
    if token:
        userid = cache.get(token)
        if userid:
            user = User.objects.get(pk=userid)
            goodsid = request.GET.get('goodsid')
            goodsnum = int(request.GET.get('goodsNum'))
            goods = Goods5.objects.get(pk=goodsid)
            # 判断需要添加的商品是否已经存在
            carts = Cart.objects.filter(user=user).filter(goods=goods)

            if carts.exists():
                cart = carts.first()
                cart.number += goodsnum
                cart.save()
            else:
                cart = Cart()
                cart.user = user
                cart.goods = goods
                cart.number = goodsnum
                cart.save()

            response_data['status'] = 1
            response_data['number'] = cart.number
            response_data['msg'] = '添加{}购物车成功:{}'.format(cart.goods.productlongname, cart.number)
            return JsonResponse(response_data)

    response_data['status'] = -1
    response_data['msg'] = '请登录后操作'
    return JsonResponse(response_data)


def addcart(request):
    goodsid = request.GET.get('goodsid')
    goods = Goods5.objects.get(pk=goodsid)

    token = request.session.get('token')
    userid = cache.get(token)
    user = User.objects.get(pk=userid)
    # 判断需要添加的商品是否已经存在
    cart = Cart.objects.filter(user=user).filter(goods=goods).first()
    cart.number += 1
    cart.save()
    response_data = {
        'msg': '添加商品成功',
        'status': 1,
        'number': cart.number,
    }
    return JsonResponse(response_data)


def subcart(request):
    goodsid = request.GET.get('goodsid')
    goods = Goods5.objects.get(pk=goodsid)

    token = request.session.get('token')
    userid = cache.get(token)
    user = User.objects.get(pk=userid)

    cart = Cart.objects.filter(user=user).filter(goods=goods).first()
    cart.number -= 1
    cart.save()

    response_data = {
        'msg': '删减商品成功',
        'status': 1,
        'number': cart.number,
    }
    return JsonResponse(response_data)


def changecartselect(request):
    cartid = request.GET.get('cartid')
    cart = Cart.objects.get(pk=cartid)
    cart.isselect = not cart.isselect
    cart.save()
    response_data = {
        'msg': '状态修改成功',
        'status': 1,
        'isselect': cart.isselect
    }

    return JsonResponse(response_data)


def changecartall(request):
    isall = request.GET.get('isall')
    token = request.session.get('token')
    userid = cache.get(token)
    user = User.objects.get(pk=userid)
    carts = user.cart_set.all()

    if isall == 'true':  # python 区分大小写
        isall = True
    else:
        isall = False
    for cart in carts:
        cart.isselect = isall
        cart.save()

    response_data = {
        'msg': '全选/取消全选 成功',
        'status': 1,
    }
    return JsonResponse(response_data)


def generate_identifier():
    temp = str(datetime.datetime.now().strftime('%Y%m%d%H%M%S')) + str(random.randrange(1000, 10000))
    return temp


def generateorder(request):
    token = request.session.get('token')
    userid = cache.get(token)
    user = User.objects.get(pk=userid)

    order = AppOrder()
    order.user = user
    order.identifier = generate_identifier()
    order.save()

    carts = user.cart_set.filter(isselect=True)
    # 创建订单商品表
    for cart in carts:
        orderGoods = AppOrdergoods()
        orderGoods.order = order
        orderGoods.goods = cart.goods
        orderGoods.number = cart.number
        orderGoods.save()
        cart.delete()

    return render(request, 'order/orderdetail.html', context={'order': order, 'user': user})


def orderlist(request):
    token = request.session.get('token')
    userid = cache.get(token)
    user = User.objects.get(pk=userid)

    orders = user.order_set.all()
    print(orders)
    return render(request, 'order/orderlist.html', context={'orders': orders})


def orderdetail(request, identifier):
    order = AppOrder.objects.filter(identifier=identifier).first()
    return render(request, 'order/orderdetail.html', context={'order': order})


def returnurl(request):
    return redirect('bbf:mine')


@csrf_exempt
def appnotifyurl(request):
    if request.method == 'POST':
        body_str = request.body.decode('utf-8')
        post_data = parse_qs(body_str)
        post_dic = {}
        for k, v in post_data.items():
            post_dic[k] = v[0]
        out_trade_no = post_dic['out_trade_no']
        AppOrder.objects.filter(identifier=out_trade_no).update(status=1)

    return JsonResponse({'msg': 'success'})


def pay(request):
    orderid = request.GET.get('orderid')
    order = AppOrder.objects.get(pk=orderid)
    sum = 0
    for orderGoods in order.ordergoods_set.all():
        sum += orderGoods.goods.price * orderGoods.number

    data = alipay.direct_pay(
        subject='八百方网上电子交易平台',  # 显示标题
        out_trade_no=order.identifier,  # 订单号
        total_amount=str(sum),  # 支付金额
        return_url='http://120.79.141.194/bbf/returnurl/'
    )

    # 支付地址
    alipay_url = 'https://openapi.alipaydev.com/gateway.do?{data}'.format(data=data)

    response_data = {
        'msg': '调用支付接口',
        'alipayurl': alipay_url,
        'status': 1
    }

    return JsonResponse(response_data)


def search(request):
    keyword = request.GET['keyword']
    result = CaoYao.objects.filter(name__contains=keyword)
    return render(request, 'index/search.html', context={'result': result})


def yijianfankui(request):
    data = {}
    token = request.session.get('token')
    userid = cache.get(token)
    if userid:
        user = User.objects.get(pk=userid)
        data['user'] = user
    return render(request, 'index/yijianfankui.html', context=data)


def submitjiyijian(request):
    # 获取上传的文件,如果没有文件,则默认为None;
    File = request.FILES.get("file", None)
    if File is None:
        return HttpResponse("no files for upload!")
    else:
        print(os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + "/static/upload/%s" % time.strftime(
            '%Y-%m-%d %H:%M:%S', time.localtime(time.time())) + File.name)
        filename = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + "/static/upload/%s" % time.strftime(
            '%Y%m%d%H%M%S', time.localtime(time.time())) + File.name
        with open(filename, 'wb+') as f:
            # 分块写入文件;
            for chunk in File.chunks():
                f.write(chunk)
        yijian = Yijian()
        yijian.ren = request.POST['ren']
        yijian.shijian = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
        yijian.neirong = request.POST['yijian']
        yijian.file = filename
        yijian.save()
        return render(request, 'index/success.html', context={'what': "意见反馈"})


def viewYijian(request):
    yijian = Yijian.objects.all()
    data = []
    for one in yijian:
        get = User.objects.get(pk=one.ren)
        onedata = {'yijian':one,'person':get}
        data.append(onedata)
    return render(request, 'admin/viewYijian.html', context={'yijian': data})


def download_file(request):
    url = request.GET['url']

    def file_iterator(file, chunk_size=512):
        with open(file, 'rb') as f:
            while True:
                c = f.read(chunk_size)
                if c:
                    yield c
                else:
                    break

    response = StreamingHttpResponse(file_iterator(url))
    response['Content-Type'] = 'application/octet-stream'
    response['Content-Disposition'] = 'attachment;filename="{0}"'.format(
        time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) + url[len(url) - 5:])
    return response
